package com.web.ShoppingDemo.action;

import java.io.ByteArrayInputStream;
import java.util.List;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.web.ShoppingDemo.model.Forder;
import com.web.ShoppingDemo.model.Product;
import com.web.ShoppingDemo.model.Sorder;

@Controller
@Scope("prototype")
public class SorderAction extends BaseAction<Sorder>{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * 将添加的货物信息暂时的存到session的购物车中
	 */
	public String addSorder(){
		//根据product.id获取相应的商品数据
		Product product = productService.get(model.getProduct().getId());
		
		//判断当前session是否有购物车,如果没有则创建
		if(session.get("forder")==null){
			session.put("forder", new Forder());
		}
		
		//把商品信息转换为sorder,并且添加到购物车(判断购物项是否重复)
		Forder forder = (Forder) session.get("forder");
		forder = sorderService.addSorder(forder, product);
		
		//计算购物的总价格
		forder.setTotal(forderService.cluTotal(forder));
		
		//把新的购物车存储到session中
		session.put("forder", forder);
		inputStream = new ByteArrayInputStream("true".getBytes());
		return "stream";
	}
	
	//对购物车中的进行删除
	public String delete(){
		//删除购物车中的商品
		Forder forder = (Forder) session.get("forder");
		
		//删除forder中的sorder
		forder = sorderService.deleteSorder(forder, model.getProduct().getId());
		
		//计算购物的总价格
		forder.setTotal(forderService.cluTotal(forder));
		
		//forder重新放回session
		session.put("forder", forder);
		//返回成功的信息
		inputStream = new ByteArrayInputStream(forder.getTotal().toString().getBytes());
		return "stream";
	}
	
	public String deleteAll(){
		session.put("forder", new Forder());
		
		inputStream = new ByteArrayInputStream("true".getBytes());
		return "stream";
	}
	/**
	 * 根据商品的编号更新商品的数量
	 * @return
	 */
	public String updateSorder(){
		Forder forder = (Forder) session.get("forder");
		sorderService.updateSorder(model, forder);
		forder.setTotal(forderService.cluTotal(forder));
		session.put("forder", forder);
		//返回新的总价格
		inputStream = new ByteArrayInputStream(forder.getTotal().toString().getBytes());
		return "stream";
	}
	/**
	 * 销量的显示
	 * @return
	 */
	public String querySale(){
		List<Object> jsonList = sorderService.querySale(model.getNumber());
		//将json对象放到栈顶
		ActionContext.getContext().getValueStack().push(jsonList);
		return "jsonList";
	}
}
